part of 'page.dart';

class _GoogleAppleStorePurchasePageWloc extends StatefulWloc<_GoogleAppleStorePurchasePageWlocState, GoogleAppleStorePurchasePage> {
  late final bloc.GoogleAppleStorePurchasePageBloc _bloc;
  late final ScrollController scrollController;

  @override
  _GoogleAppleStorePurchasePageWlocState get initialState {
    return _GoogleAppleStorePurchasePageWlocStateFactory().create(
      blocState: _bloc.state,
    );
  }

  void onPurchaseItemTileTap({
    required String purchaseItemSku,
  }) {
    _bloc.selectPurchaseItem(
      purchaseItemSku: purchaseItemSku,
    );
  }

  void onPurchaseRequestButtonPressed() {
    _bloc.requestPurchase();
  }

  void onPrivacyPolicyTap() {
    _bloc.openPrivacyPolicy();
  }

  void onTermsOfUseTap() {
    _bloc.openTermsOfUse();
  }

  void _onBlocStateChanged(bloc.GoogleAppleStorePurchasePageBlocState blocState) {
    final updatedState = _GoogleAppleStorePurchasePageWlocStateFactory().create(
      blocState: blocState,
    );

    emit(updatedState);

    if (Config().productionUIEnabled && blocState.premiumAccessActive) {
      Navigator.of(context).pop();
    }
  }

  void _onScrollChanged() {
    setState(() {});
  }

  @override
  void initState() {
    super.initState();

    _bloc = bloc.GoogleAppleStorePurchasePageBloc(
      googleAppleStorePurchaseBloc: core_di.sl(),
      googleAppleStorePurchaseFlowDisplayBloc: core_di.sl(),
      userInfoBloc: core_di.sl(),
      urlLauncherBloc: core_di.sl(),
      initialize: google_apple_store_purchase_page_di.sl(),
    );

    _bloc.stream.listen(_onBlocStateChanged);

    scrollController = ScrollController();
    scrollController.addListener(_onScrollChanged);
  }

  @override
  void dispose() {
    _bloc.close();
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _GoogleAppleStorePurchasePageView(
      wloc: this,
    );
  }
}
